<?php
class PresentationRelation extends Presentation {
    protected $table;
    protected $primaryKey;
    protected $displayField;
    protected $canBeNull;
    
    public function __construct($table, $primaryKey, $displayField,
            $canBeNull = false) {
        $this->table = $table;
        $this->primaryKey = $primaryKey;
        $this->displayField = $displayField;
        $this->canBeNull = $canBeNull;
    }
    
    public function fixInput($current, $rawInput) {
        if (!$rawInput && $this->canBeNull) {
            return null;
        }
        return $current;
    }
    
    public function formatFormField(&$field) {
        $field['type'] = 'select';
        $options = array();
        $this->canBeNull && ($options[''] = '---');
        $cols = array($this->primaryKey, $this->displayField);
        $order = array($this->primaryKey);
        $data = &$this->dbdriver->select($this->table, $cols, '', $order);
        foreach ($data as &$row) {
            $options[$row[$this->primaryKey]] = $row[$this->displayField];
        }
        $field['options'] = &$options;
        $field['selected'] = $field['value'];
    }
    
    public function formatForList($value) {
        if (!$value) {
            return '---';
        }
        $cols = array($this->displayField);
        $value = &$this->dbdriver->select($this->table, $cols,
                '`' . $this->primaryKey . '` = ' . (int) $value);
        return isset($value[0]) ? $value[0][$this->displayField] : '---';
    }
}